<template>
  <div class="media-management">
    <h2>媒体管理</h2>
    
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :inline="true" :model="queryParams" @submit.prevent>
        <el-form-item label="所属活动">
          <el-select v-model="queryParams.activityId" placeholder="请选择活动" clearable
                    filterable>
            <el-option
              v-for="activity in activityOptions"
              :key="activity.id"
              :label="activity.title ? `${activity.title} (ID:${activity.id})` : `活动${activity.id}`"
              :value="activity.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="媒体类型" style="width: 300px">
          <el-select v-model="queryParams.mediaType" placeholder="请选择媒体类型" clearable>
            <el-option label="图片" value="photo"></el-option>
            <el-option label="视频" value="video"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
          >
          </el-date-picker>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 操作按钮 -->
    <div class="operation-container">
      <el-button type="primary" @click="handleAdd" v-if="isAdmin || isClubLeader">添加媒体</el-button>
    </div>
    
    <!-- 媒体表格 -->
    <el-table v-loading="loading" :data="mediaList" border stripe style="width: 100%">
      <el-table-column prop="id" label="ID" width="60"></el-table-column>
      <el-table-column label="所属活动" width="180">
        <template #default="scope">
          {{ scope.row.activity ? scope.row.activity.title : '-' }}
        </template>
      </el-table-column>
      <!-- <el-table-column prop="mediaType" label="媒体类型" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.mediaType === 'photo' ? 'success' : 'warning'">
            {{ scope.row.mediaType === 'photo' ? '图片' : '视频' }}
          </el-tag>
        </template>
      </el-table-column> -->
      <el-table-column label="媒体预览" width="150">
        <template #default="scope">
          <div v-if="scope.row.mediaType === 'photo'">
            <el-image 
              style="width: 100px; height: 60px"
              :src="getMediaUrl(scope.row.mediaUrl)" 
              :preview-src-list="[getMediaUrl(scope.row.mediaUrl)]"
              fit="cover"
            ></el-image>
            <!-- <img src="/src/assets/d06bd493-2376-4bc0-b026-544542cb88c4_photo.png" alt=""> -->
          </div>
          <div v-else>
            <el-button link type="primary" @click="previewVideo(scope.row)">预览视频</el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="mediaUrl" label="媒体URL" show-overflow-tooltip></el-table-column>
      <el-table-column prop="uploadTime" label="上传时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.uploadTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150">
        <template #default="scope">
          <el-button link type="primary" @click="handleEdit(scope.row)"
                    v-if="isAdmin || (isClubLeader && canManageMedia(scope.row))">编辑</el-button>
          <el-button link type="danger" @click="handleDelete(scope.row)"
                    v-if="isAdmin || (isClubLeader && canManageMedia(scope.row))">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="queryParams.page"
        :page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 视频预览弹窗 -->
    <el-dialog
      v-model="videoDialogVisible"
      title="视频文件位置"
      width="800px"
      destroy-on-close
    >
      <!-- 显示视频完整链接 -->
      <div class="video-link-container">
        <div class="video-link-title">本地文件路径：</div>
        <div class="video-link-content">
          <el-input 
            type="text" 
            v-model="fullVideoUrl" 
            readonly
            :autosize="{ minRows: 1, maxRows: 3 }"
          ></el-input>
          <el-button type="primary" size="small" @click="copyVideoUrl">复制路径</el-button>
        </div>
        <div class="video-link-steps">
          <p><strong>在浏览器中打开视频的方法：</strong></p>
          <ol>
            <li>复制上面的文件路径</li>
            <li>打开新的浏览器标签页</li>
            <li>粘贴路径到地址栏并访问</li>
          </ol>
        </div>
        <div class="video-link-tip">
          <el-alert
            title="提示：使用本地文件路径访问视频可能需要浏览器权限"
            type="info"
            show-icon
            :closable="false"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMediaList, deleteMedia } from '@/api/media'
import { getActivityList } from '@/api/activity'
import { useUserStore } from '@/store/user'
import { getMediaUrl } from '@/utils/mediaUrl'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const mediaList = ref([])
const total = ref(0)
const activityOptions = ref([])
const dateRange = ref([])
const videoDialogVisible = ref(false)
const currentVideo = ref('')
const videoErrorMsg = ref('')
const fullVideoUrl = ref('')

// 用户信息
const userInfo = computed(() => userStore.userInfo)
const isAdmin = computed(() => userInfo.value.role === 'admin')
const isClubLeader = computed(() => userInfo.value.role === 'club_leader')

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  activityId: null,
  mediaType: '',
  startTime: null,
  endTime: null
})

// 判断当前用户是否可以管理该媒体
const canManageMedia = (media) => {
  if (!isClubLeader.value || !media || !media.activity) return false
  
  // 如果是社团负责人，只能管理自己社团的活动的媒体
  const clubId = media.activity.clubId
  if (clubId) {
    // 假设我们有一个方法来获取用户管理的社团ID列表
    // 这里简化处理，实际应该从clubOptions中过滤出用户是负责人的社团
    return true // 在实际情况中应该检查该社团是否由当前用户管理
  }
  
  return false
}

// 监听日期范围变化
watch(dateRange, (newValue) => {
  if (newValue && newValue.length === 2) {
    queryParams.startTime = newValue[0]
    queryParams.endTime = newValue[1]
  } else {
    queryParams.startTime = null
    queryParams.endTime = null
  }
})

// 获取媒体列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getMediaList(queryParams)
    if (res.data && res.code === 200) {
      mediaList.value = res.data.list
      total.value = res.data.total
    } else {
      ElMessage.error(res.message || '获取媒体列表失败')
    }
  } catch (error) {
    console.error('获取媒体列表出错:', error)
    ElMessage.error('获取媒体列表失败')
  } finally {
    loading.value = false
  }
}

// 加载活动列表
const loadActivities = async () => {
  try {
    const res = await getActivityList({ pageSize: 1000 })
    if (res.data && res.code === 200) {
      activityOptions.value = res.data.list
      console.log('活动列表数据:', activityOptions.value)
    } else {
      ElMessage.error(res.message || '获取活动列表失败')
    }
  } catch (error) {
    console.error('获取活动列表出错:', error)
    ElMessage.error('获取活动列表失败')
  }
}

// 预览视频
const previewVideo = (row) => {
  // 检查URL格式
  let videoUrl = row.mediaUrl;
  
  // 如果是相对路径（以/uploads/开头），转换为本地文件路径
  if (videoUrl.startsWith('/assets/')) {
    // 提取文件名部分
    const fileName = videoUrl.substring('/assets/'.length);
    // 构建完整的本地文件路径
    videoUrl = `D:/javaweb/gaoxiaosys2.0/frontend/src/assets/${fileName}`;
  }

  // 设置视频完整URL
  fullVideoUrl.value = videoUrl;
  
  // 打开预览弹窗
  videoDialogVisible.value = true;
  
  // 打印视频URL用于调试
  console.log('预览视频URL:', videoUrl);
}

// 复制视频链接
const copyVideoUrl = () => {
  if (!fullVideoUrl.value) {
    ElMessage.warning('没有可复制的路径');
    return;
  }
  
  // 使用navigator.clipboard API复制文本
  navigator.clipboard.writeText(fullVideoUrl.value)
    .then(() => {
      ElMessage.success('文件路径已复制到剪贴板');
    })
    .catch(err => {
      console.error('复制失败:', err);
      ElMessage.error('复制失败，请手动选择并复制');
      
      // 备用方案：选择输入框内容
      const input = document.querySelector('.video-link-content input');
      if (input) {
        input.select();
        try {
          document.execCommand('copy');
          ElMessage.success('文件路径已复制到剪贴板');
        } catch (e) {
          ElMessage.error('复制失败，请手动选择并复制');
        }
      }
    });
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  getList()
}

// 重置
const handleReset = () => {
  queryParams.activityId = null
  queryParams.mediaType = ''
  dateRange.value = []
  queryParams.startTime = null
  queryParams.endTime = null
  queryParams.page = 1
  getList()
}

// 添加媒体
const handleAdd = () => {
  router.push('/media/add')
}

// 编辑媒体
const handleEdit = (row) => {
  router.push(`/media/edit/${row.id}`)
}

// 删除媒体
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除该媒体吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await deleteMedia(row.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除媒体出错:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.page = page
  getList()
}

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 初始化
onMounted(() => {
  loadActivities()
  getList()
  
})
</script>

<style scoped>
.media-management {
  padding: 20px;
}

.search-form {
  background-color: #f5f7fa;
  padding: 18px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.operation-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.video-error {
  color: #f56c6c;
  margin-top: 10px;
  text-align: center;
  padding: 10px;
  background-color: #fef0f0;
  border-radius: 4px;
}

.video-link-container {
  padding: 20px;
}

.video-link-title {
  font-weight: bold;
  margin-bottom: 10px;
}

.video-link-content {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.video-link-content .el-input {
  flex: 1;
}

.video-link-steps {
  margin-bottom: 10px;
}

.video-link-tip {
  margin-top: 10px;
  font-size: 14px;
  color: #909399;
}
</style> 